package pers.itqiqi.spring5;

import pers.itqiqi.spring5.dao.UserDao;
import pers.itqiqi.spring5.dao.impl.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author kevin_琪琪
 * @version 1.0
 * @description
 * @date 2022-06-27 15:10
 */
public class JDKProxy {

    public static void main(String[] args) {

        // 创建接口实现类的代理对象
        Class[] interfaces =  {UserDao.class};
        UserDao userDao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {

            private final UserDaoImpl userDao = new UserDaoImpl();

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // 方法执行前
                System.out.println("方法执行前,方法名:" + method.getName() + " :传递的参数..." + Arrays.toString(args));
                // 被增强的方法执行
                Object res = method.invoke(userDao, args);
                // 方法调用之后
                System.out.println(("方法之后执行...." + userDao));

                return res;
            }

        });

        int result = userDao.add(1, 2);
        System.out.println("result=" + result);

    }
}
